package logic

import (
	"cart/cart"
	"context"
	"fmt"
	"goods_srv/goods"
	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddCartLogic) AddCart(req *types.AddCartRequest) (resp *types.Response, err error) {
	details, err := l.svcCtx.GoodsSrv.GetGoodsDetails(l.ctx, &goods.GetGoodsDetailsReq{GoodsId: req.GoodsId})
	if err != nil {
		return &types.Response{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}
	if details.GoodsId == 0 {
		return &types.Response{
			Code: -2,
			Msg:  "商品不存在",
			Data: nil,
		}, err
	}
	//判断库存是否充足
	res, err := l.svcCtx.GoodsSrv.GetGoodsStock(l.ctx, &goods.GetGoodsStockReq{GoodsId: req.GoodsId})
	if res.GoodsStock > req.Num {
		return &types.Response{
			Code: -3,
			Msg:  "商品库存不足",
			Data: nil,
		}, err
	}
	userId := l.ctx.Value("userId").(string)
	uid, _ := strconv.Atoi(userId)
	fmt.Println(uid)
	//添加购物车
	_, err = l.svcCtx.CartSrv.AddCart(l.ctx, &cart.AddCartReq{
		UserId:     int64(uid),
		GoodsId:    req.GoodsId,
		GoodsTitle: details.GoodsTitle,
		GoodsPrice: details.GoodsPrice,
		Num:        req.Num,
	})
	if err != nil {
		return &types.Response{
			Code: -4,
			Msg:  "服务器内部错误",
			Data: nil,
		}, nil
	}
	return &types.Response{
		Code: 0,
		Msg:  "购物车添加成功",
		Data: nil,
	}, nil
}
